package com.tbit.uqbike.client.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.tbit.uqbike.client.constant.AccountConfigExtConstant;
import com.tbit.uqbike.client.dao.core.MachineFaultDao;
import com.tbit.uqbike.client.dao.huge.ImageDao;
import com.tbit.uqbike.client.dao.log.MachineFaultLogDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.AccountConfigExt;
import com.tbit.uqbike.client.service.AccountConfigService;
import com.tbit.uqbike.client.service.CacheService;
import com.tbit.uqbike.client.service.FeeAppealService;
import com.tbit.uqbike.client.service.MachineFaultService;
import com.tbit.uqbike.client.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 11:20 2020/1/15
 */
@Service("machineFaultService")
public class MachineFaultServiceImpl implements MachineFaultService {
    @Autowired
    private MachineFaultDao machineFaultDao;
    @Autowired
    private ImageDao imageDao;
    @Autowired
    private FeeAppealService feeAppealService;
    @Autowired
    private MachineFaultLogDao machineFaultLogDao;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private CacheService cacheService;

    @Override
    public void insert(MultipartFile[] files, MachineFault machineFault, HttpServletRequest request, User user, Machine machine) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        StringBuffer name = new StringBuffer();
        /* 判断是否是文件上传 */
        if (multipartResolver.isMultipart(request)) {
            if (files.length > 0) {
                for (MultipartFile file : files) {
                    if (file.getSize() > 2 * 1024 * 1024) {
                        throw new BaseException("-4003", "图片过大");
                    }
                    String fileName = feeAppealService.ossFileUpload(file, user.getAccountId());
                    name.append(fileName).append(";");
                }
            }
        }

        if (name.length() > 1) {
            name.delete(name.length() - 1, name.length());
        }
        //查询该车辆最新的一条故障上报记录
        MachineFaultLog newestMachineFaultLog = machineFaultLogDao.selectNewestLog(machine.getMachineId());
        String orderNO = IdUtil.objectId();
        if (newestMachineFaultLog != null && StringUtils.hasText(newestMachineFaultLog.getOrderNO())
                && !newestMachineFaultLog.getFaulttype().equals(4) && !newestMachineFaultLog.getFaulttype().equals(3)) {
            orderNO = newestMachineFaultLog.getOrderNO();
        }
        String nowTime = DateTimeUtil.getNowTime();
        machineFault.setUpdateTime(nowTime);
        machineFault.setImageIds(name.toString());
        MachineFaultLog machineFaultLog = new MachineFaultLog();
        machineFaultLog.setAccountId(machine.getAccountId())
                .setMachineId(machine.getMachineId())
                .setUserCode(machine.getUserCode())
                .setAddManid(user.getUserId())
                .setAddManName(user.getName())
                .setAddManPhone(user.getPhone())
                .setAddTime(DateUtil.parse(nowTime, "yyyy-MM-dd HH:mm:ss"))
                .setFaults(machineFault.getFaults())
                .setImageIds(name.toString())
                .setIntoMain(1)
                .setPoint(machineFault.getPoint())
                .setFaulttype(5)
                .setMachineType(machine.getMachineType())
                .setRemark(machineFault.getRemark())
                .setOrderNO(orderNO);
        machineFaultLogDao.insert(machineFaultLog);
        //兼容用户x天内上报y次故障车辆是否可再次借出
        AccountConfig accountConfig = accountConfigService.getByAccountId(machine.getAccountId());
        if (accountConfig != null) {
            AccountConfigExt dayConfigExt = cacheService.getAccountConfigExtByKey(machine.getAccountId(), AccountConfigExtConstant.USER_SIGN_FAULT_DAY);
            AccountConfigExt countConfigExt = cacheService.getAccountConfigExtByKey(machine.getAccountId(), AccountConfigExtConstant.USER_SIGN_FAULT_COUNT);
            if (dayConfigExt == null || countConfigExt == null) {
                //兼容旧数据，给默认值
                dayConfigExt = new AccountConfigExt(machine.getAccountId(), AccountConfigExtConstant.USER_SIGN_FAULT_DAY, "30", null, null);
                countConfigExt = new AccountConfigExt(machine.getAccountId(), AccountConfigExtConstant.USER_SIGN_FAULT_COUNT, "5", null, null);
            }
            //满足条件且实时表没有则添加到实时表
            if (Integer.parseInt(dayConfigExt.getParamValue()) > 0) {
                Integer count = machineFaultLogDao.getCountByMachineIdAndDay(machineFault.getMachineId(), Integer.parseInt(dayConfigExt.getParamValue()), Integer.parseInt(countConfigExt.getParamValue()));
                if (count > 0) {
                    //machineFaultDao.getByMachineId(machineFault.getMachineId());
                    MachineFault machineFaultInDb = this.checkMachineSuspectedFault(machineFault.getMachineId());
                    if (machineFaultInDb == null) {
                        machineFault.setOrderNO(orderNO);
                        machineFaultDao.insert(machineFault);
                    }
                }
            }
        }

    }

    @Override
    public MachineFault getByMachineId(Integer machineId) {
        return machineFaultDao.getByMachineId(machineId);
    }

    /**
     * @description: 直接添加车辆故障
     * @author: mo.shanyong
     * @date: 2025/5/13 15:29
     * @param: machineFault
     */
    @Override
    public void add(MachineFault machineFault) {
        machineFaultDao.insert(machineFault);
    }

    /**
     * @description: 根据车辆id删除车辆的故障信息
     * @author: mo.shanyong
     * @date: 2025/5/13 15:57
     * @param: machineId
     */
    @Override
    public void del(Integer machineId) {
        machineFaultDao.del(machineId);
    }

    /**
     * @description: 检查故障是否是疑似故障，如果是疑似故障则删除掉疑似故障，把正式的故障加入
     * @author: mo.shanyong
     * @date: 2025/5/13 16:51
     * @param: machineId
     * @return: com.tbit.uqbike.client.pojo.MachineFault
     */
    private MachineFault checkMachineSuspectedFault(Integer machineId){
        MachineFault machineFaultInDb = machineFaultDao.getByMachineId(machineId);
        //故障为空，或者不是疑似故障，则直接返回
        if (Objects.isNull(machineFaultInDb) || !Objects.equals(machineFaultInDb.getFrom(),4)){
            return machineFaultInDb;
        }
        machineFaultDao.del(machineFaultInDb.getMachineId());
        return null;
    }
}
